package cn.eeany.zutools

import cn.hutool.core.date.DateUtil
import cn.hutool.core.io.IORuntimeException
import cn.hutool.http.HttpRequest
import cn.hutool.json.JSONArray
import cn.hutool.json.JSONObject
import cn.hutool.json.JSONUtil
import groovy.transform.Field

import java.awt.*
import java.awt.event.KeyEvent
import java.util.concurrent.atomic.AtomicInteger

@Field AtomicInteger skip = new AtomicInteger(1)
@Field def tpNodeId
//授权信息
@Field def Authorization = "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ4dXBpbmciLCJjcmVhdGVkIjoxNjMxNTg2NTIwOTk1LCJleHAiOjE2MzIxOTEzMjAsInVzZXJJZCI6IjEzNTQifQ.5iBIvtbtb00OrqR4YZZl2vHi4JssJXl0l05k7OKUGd4ZyonyvnkAJ_rPp4WSigrQ-xlxHMVgpNmEtTKBMMiigg"
@Field def wrCode
@Field def wrCodeTemp
@Field def versionId
//当前节点名称
@Field def nodeName
@Field def orderUrl = "https://devbase.xinbeiyang.info/workorderapi"
//@Field def userId="-1"
@Field def userId = "1354"
//@Field def userName="超级管理员"
@Field def userName = "xuping2"
//外部工单
@Field def outWrCode = "123123123123123130${DateUtil.currentSeconds()}"
//外部工单号
@Field def outWrId = "123123asd1213s4${DateUtil.currentSeconds()}"
//调试模式
@Field def isdebug = false


wrCode = createThireWr()


sayHi(wrCode)

sayHi("查询工单${wrCode}")
sayHi(searchOrderByCode())

sayHi(getnextnode())
sayHi("流程开始--->接单")
sayHi(jiedan())
sayHi(getnextnode())
assertStatus("接单")
sayHi("流程开始--->出发")
sayHi(chufa())
sayHi(getnextnode())
assertStatus("出发")
sayHi("流程开始--->到达")
sayHi(daoda())
sayHi(getnextnode())
assertStatus("到达")
sayHi("流程开始--->开始")
sayHi(kaishi())
sayHi(getnextnode())

assertStatus("开始")
sayHi("流程开始--->完成")
sayHi(wanchceng())
sayHi(getnextnode())
assertStatus("完成")
sayHi("流程开始--->驳回")
sayHi(bohui())
sayHi(getnextnode())
assertStatus("完成")

sayHi("流程开始--->开始")
sayHi(kaishi())
sayHi(getnextnode())
assertStatus("开始")
sayHi("流程开始--->完成")
sayHi(wanchceng())
sayHi(getnextnode())
assertStatus("完成")


sayHi("流程开始--->验证通过")
sayHi(yanzhengtongguo())
sayHi(getnextnode())
assertStatus("验收")

sayHi("流程开始--->返程出发")
sayHi(fanchengchufa())
sayHi(getnextnode())
assertStatus("返程出发")
sayHi("流程开始--->返程出发")
sayHi(fanchengchufa())
sayHi(getnextnode())
assertStatus("返程到达")
//

def fanchengchufa() {
    return gongdanBastPost("""{"nodeId":"${tpNodeId}","wrCode":"${wrCode}","optState":null,"userId":"${userId}","optName":"${userName}","versionId":${versionId},"location":{"locAddress":"【PC端操作】,无地理位置信息","locDistance":"","longitude":"","latitude":""},"formMessage":{}}""")
}

def fanchengjieshu() {
    return gongdanBastPost("""{"nodeId":"${tpNodeId}","wrCode":"${wrCode}","optState":null,"userId":"${userId}","optName":"${userName}","versionId":${versionId},"location":{"locAddress":"【PC端操作】,无地理位置信息","locDistance":"","longitude":"","latitude":""},"formMessage":{}}""")
}


def assertStatus(String src) {
    if (src.equals(nodeName)) {
        println "流程 ${nodeName} ----> ok"
    } else {
        println("---------------------------------流程 期望 ${src}    实际上是：${nodeName}---->  error")
        sayHi("流程开始--->暂停")
        sayHi(zanting())
        sayHi(getnextnode())
    }
}

def sayHi(def something) {
    println("====${new Date()}========${skip.get()}=============")
    println(something)
    println("============${skip.getAndIncrement()}=============")
}

def getnextnode() {
    JSONObject re = JSONUtil.parseObj(postDev("${orderUrl}/process/workOrder/show", """{"wrCode":"${wrCode}"}"""))
    JSONObject result = re.getJSONObject("result")
    JSONObject currentNode = result.getJSONObject("currentNode")
    JSONObject workOrder = result.getJSONObject("workOrder")
    versionId = workOrder.getStr("versionId")

    if (result.getStr("nextNode").startsWith("[")) {
        JSONArray nextNodes = result.getJSONArray("nextNode")
        JSONObject nextNode = nextNodes.getJSONObject(0)
        tpNodeId = nextNode.getLong("tpNodeId")
    }
    nodeName = currentNode.get("nodeName")
    return [wrCode, tpNodeId, nodeName]
}


def searchOrderByCode() {
    String searchOrderJson = """{"wrCode":"${wrCode}","wrName":"","repairPlace":null,"repairVisitTime":null,"orgId":null,"logSendCode":"","thirdOrderId":"","orgName":"","num_page":1,"num_size":10}"""
    return JSONUtil.parse(postDev("${orderUrl}/workorder/core/workorder/listAll?pageSize=10&pageNum=1", searchOrderJson))
}

def chufa() {
    return gongdanBastPost("""{"nodeId":"${tpNodeId}","wrCode":"${wrCode}","optState":null,"userId":"${userId}","optName":"${userName}","versionId":${versionId},"location":{"locAddress":"【PC端操作】,无地理位置信息","locDistance":"","longitude":"","latitude":""},"formMessage":{}}""")
}

def daoda() {
    return gongdanBastPost(
            """{"nodeId":"${tpNodeId}","wrCode":"${wrCode}","optState":null,"userId":"${userId}","optName":"${userName}","versionId":${versionId},"location":{"locAddress":"【PC端操作】,无地理位置信息","locDistance":"","longitude":"","latitude":""},"formMessage":{}}"""
    )
}

def kaishi() {
    return gongdanBastPost("""{"nodeId":"${tpNodeId}","wrCode":"${wrCode}","optState":null,"userId":"${userId}","optName":"${userName}","versionId":${versionId},"location":{"locAddress":"【PC端操作】,无地理位置信息","locDistance":"","longitude":"","latitude":""},"formMessage":{}}""")
}


def yanzhengtongguo() {
    String postJson = """{
    "coustomerNO": "HL001",
    "coustomerName": "哈啰换电",
    "dataSource": "HL",
    "dataType": "sync_repair_order_process",
    "syncDate": "2021-11-23 13:40:02",
    "syncList": [
      {
        "createTime": "2021-11-24 18:43:02",
        "currentProgress": "3",
        "operLoginName": "XBY0001",
        "operName": "${userName}",      
        "remark": "哈啰判责通过",
      "outWrCode": "${outWrCode}",
      "outWrId": "${outWrId}"
      }
    ],
    "syncNum": "20191025000003"
}
  """
    return postDev("${orderUrl}/out/workorder/sycmsg", postJson)
}


def bohui() {
    String postJson = """{
  "coustomerNO": "HL001",
  "coustomerName": "哈啰换电",
  "dataSource": "HL",
  "dataType": "sync_repair_order_process",
  "syncDate": "2021-11-23 13:40:02",
  "syncList": [
    {
      "createTime": "2021-11-23 13:40:02",
      "currentProgress": "100",
      "operStatus": "1",
      "finishStatus": "0",
      "operLoginName": "XBY0001",
      "operName": "${userName}",      
      "remark": "哈啰判责驳回,责任方不明确",
      "outWrCode": "${outWrCode}",
      "outWrId": "${outWrId}"
    }
  ],
  "syncNum": "20191025000004"
}
  """
    return postDev("${orderUrl}/out/workorder/sycmsg", postJson)
}

def zanting() {
    String postJson = """{
  "nodeId": "${tpNodeId}",
  "wrCode": "${wrCode}",
  "optState": "",
  "userId": "${userId}",
  "optName": "${userName}",
  "versionId": ${versionId},
  "location": {
    "locAddress": "【PC端操作】,无地理位置信息",
    "locDistance": "",
    "longitude": "",
    "latitude": "",
    "otherOperate": "pause",
    "pigeonholed": "支撑部门",
    "proDescExt": "外包人员未到",
    "proDesc": "阿萨德阿萨德阿萨德"
  },
  "formMessage": {}
}
"""
    return gongdanBastPost(postJson)
}

def jiedan() {
    String postJson = """{
  "nodeId": "${tpNodeId}",
  "wrCode": "${wrCode}",
  "optState": null,
  "userId": "${userId}",
  "optName": "${userName}",
  "versionId": ${versionId},
  "location": {
    "locAddress": "【PC端操作】,无地理位置信息",
    "locDistance": "",
    "longitude": "",
    "latitude": ""
  },
  "formMessage": {}
}
"""
    def re = gongdanBastPost(postJson)

    if (re?.message?.contains("用户存在正在运行的工单")) {
        String msg = re.message
        wrCodeTemp = wrCode
        wrCode = msg.substring(msg.indexOf("【") + 1, msg.indexOf("】"))
        sayHi("当前用户存储在工单需要暂停工单  ${wrCode}")
        getnextnode()
        zanting()
        sayHi("暂停  ${wrCode}")
        wrCode = wrCodeTemp
        getnextnode()
        sayHi("继续接单")
        jiedan()
    }
    return re
}


def wanchceng() {
    String postJson = """{
  "nodeId": "${tpNodeId}",
  "wrCode": "${wrCode}",
  "optState": null,
  "userId": "${userId}",
  "optName": "${userName}",
  "versionId": ${versionId},
  "location": {
    "locAddress": "【PC端操作】,无地理位置信息",
    "locDistance": "",
    "longitude": "",
    "latitude": ""
  },
  "formMessage": {
    "212": {
      "sop": {
        "repairReason": "",
        "timeoutReason": "",
        "assetLongitude": "",
        "assetLatitude": "",
        "assetProvince": "北京市",
        "assetCity": "北京市",
        "assetCounty": "西城区",
        "assetLocation": "北三环中路11号",
        "originLocation": "北京市/北京市/西城区 北三环中路11号",
        "assetNetwork": "我们的生活方式是",
        "judModelName": "工控机模块",
        "judSymbolName": "主板指示灯不亮",
        "judReasonName": "电源线故障",
        "coustomerName": "湖南中晟智造实业发展有限公司",
        "coustomerNo": "C25725",
        "assetCode": "BCVM-RI2000180707500023",
        "assetId": "56b08b4642ca1a77c4b2d31993bfaeb5",
        "judClassValue": "新零售",
        "judTypeValue": "智能微超",
        "productModel": "1175",
        "productModelName": "BCVM-RI2000",
        "judModelValue": 5794,
        "judSymbolValue": 5807,
        "judReasonValue": 5811,
        "judDes": "阿萨德阿萨德",
        "judCauseDesc": "",
        "guaranteeState": "1",
        "whetherFee": 1,
        "withoutFeeCause": "",
        "faultTypeCode": "1",
        "faultTypeName": "固件问题",
        "sopFrom": "snbc_sop_adn_fee;",
        "isSelectinvoiceTitle": true,
        "isWhetherFee": true,
        "isSelectSop": true,
        "causeInputIsDisabled": {
          "repairReason": false,
          "timeoutReason": false
        }
      },
      "fee_data": {
        "detail": [
          {
            "label": "9.5.30.0000007-B",
            "feeDesc": "Pb-free,104mm嵌入式热敏打印机,BK-T6112通用配置（顺丰4寸）,带串口线,无底座配置散包装,USB+串口,19200bps,200,通道宽度:104mm,标签纸,带电源转接线,带电源,不带电源线,带2.5M白色串口线,下打",
            "count": 77,
            "feeType": 2,
            "statusCode": 2,
            "feeName": "9.5.30.0000007",
            "fee": 0,
            "errInfo": "系统不存在该配件的成本价,无法计算。",
            "upFeeStatus": false,
            "moneyCount": 0,
            "fee_count": 1,
            "feetstate": "2",
            "isShowRecycle": true,
            "putDownlabel": "9.5.30.0000007-B",
            "putDownMaterialCode": "9.5.30.0000007",
            "downFee": 0,
            "putDownMateriaDescribe": "Pb-free,104mm嵌入式热敏打印机,BK-T6112通用配置（顺丰4寸）,带串口线,无底座配置散包装,USB+串口,19200bps,200,通道宽度:104mm,标签纸,带电源转接线,带电源,不带电源线,带2.5M白色串口线,下打",
            "putDownMaterialNum": 1,
            "put_DownMaterialPrice": 0,
            "recoverType": 1,
            "isChangeCause": false,
            "downFeeErrinfo": null,
            "downFeeErrinfo2": null,
            "errInfo2": "无法关联价格,请联系服务运营部-刘认认,电话:0631-5709148进行人工核算",
            "feetext": "系统不存在该配件的成本价,无法计算。无法关联价格,请联系服务运营部-刘认认,电话:0631-5709148进行人工核算",
            "errFeeState": "2",
            "widget_maxupcount": 1,
            "feeCount": 1,
            "payMoney": 0,
            "putDownMaterialPrice": 0
          }
        ],
        "needPayMoney": 0,
        "payMoney": 0,
        "invoiceRemark": "",
        "needInvoice": "0",
        "invoiceType": "0",
        "invoiceTitle": "",
        "invoiceComponeyCode": null,
        "invoiceNum": "",
        "invoiceAddress": "",
        "invoiceOpenBank": "",
        "invoiceAccount": "",
        "invoiceTel": "",
        "normalOperation": 2,
        "invoice_remark_show": false
      },
     "dict":{
        "responsibleParty":{
            "valueCode":"1",
            "valueName":"责任不明确"
        }
      },
      "work_order": { "wrDesc": "阿萨德阿萨德" },
       "workOrderPicStr": "http://snbc-smcp.oss-cn-hangzhou.aliyuncs.com/workorderpic/20210910/weixin/uploadImg/workorderpic/20210910/1381/HLGD20210910000014_11631262130318.jpg,http://snbc-smcp.oss-cn-hangzhou.aliyuncs.com/workorderpic/20210910/weixin/uploadImg/workorderpic/20210910/1381/HLGD20210910000014_21631262130667.jpg"
    }
  }
}
"""

    return gongdanBastPost(postJson)
}

def gongdanBastPost(String postJson) {
    return JSONUtil.parseObj(
            postDev("${orderUrl}/process/workOrder/save", postJson)
    )
}


def createThireWr() {


    String jsonString = """{
  "coustomerNO": "HL001",
  "coustomerName": "哈啰换电",
  "dataSource": "HL",
  "dataType": "sync_repair_order",
  "syncDate": "2021-04-22 09:47:04",

  "syncList": [
    {
      "outWrCode": "${outWrCode}",
      "outWrId": "${outWrId}",
      "assetCode": "TXKDG200001",
      "assetFactoryCode":"BCVM-RI2000180707500023",
      "province": "上海市",
      "city": "上海市",
      "county": "青浦区",
      "address": "上海市青浦区华南路1908号",
      "createCode": "creater",
      "createDate": "${DateUtil.now()}",
      "createName": "zuaa",
      "createPhone": "18964764425",
      "prefix": "HLGD",
      "repairVisitTime": "2022-01-02 00:00:00",
      "wrName": "哈啰维修工单",
      "remark": "", 
      "extendAttr": { "processBranch": "sync_repair_order_hl" }
    }
  ],
  "syncNum": "20191025000001"
}"""
    result2 = postDev("${orderUrl}/out/third_workorder", jsonString)
    if (result2.contains("status=500")) {
        sayHi("服务构建中.....")
        System.exit(0)
    }

    def res2 = JSONUtil.parseObj(result2)
    println(res2.get("result"))

    def wr_codeJsonList = res2.get("result")
    def wr_code_obj = JSONUtil.parseArray(wr_codeJsonList)
    if (wr_code_obj.size() <= 0) {
        println("没有发现工单号")
        return
    }
    wrCode = wr_code_obj.get(0)
    return wrCode
}

def getDev(String url) {
    String result2 = HttpRequest.get(url)
            .header("Authorization", "${Authorization}")
            .header("Content-Type", "application/json")
            .execute().body()
    return result2
}

def postDev(String url, String jsonString) {
    String result2 = ""


    try {
        result2 = HttpRequest.post(url)
                .body(jsonString).header("Authorization", "${Authorization}")
                .header("Content-Type", "application/json").timeout(30_000)
                .execute().body()
        if (isdebug) {
            sayHi(result2)
        }
    } catch (IORuntimeException e) {
        if (e != null) {
            sayHi("网络超时,呼叫热键-ctrl+. 启动wifi网络")
            wifiNet()
            sleep(1000 * 10)
            sayHi("网络超时,等待网络切换试")
            postDev(url, jsonString)
        }
    }
    return result2
}


static def wifiNet() {
    Robot robot = new Robot()
    robot.keyPress(KeyEvent.VK_CONTROL)
    robot.keyPress(KeyEvent.VK_DECIMAL)
    sleep(1000)
    robot.keyRelease(KeyEvent.VK_DECIMAL)
    robot.keyRelease(KeyEvent.VK_CONTROL)
}